package com.zwcl.payment.gateway.utils;

import com.zwcl.common.core.utils.SpringUtils;
import com.zwcl.payment.gateway.constants.PayConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @Description 重试工具
 * @Author guobaikun
 * @Date 2020/4/3 15:44
 * @Email kunye.guo@wetax.com.cn
 */
@Slf4j
public class RetryUtils {

    public static final int retryCount = 5;//默认重试次数

    /**
     * 企业付款重试
     * @param tradeNo   交易流水号
     * @param times     重试次数
     * @return  是否需要重试
     */
    public static Boolean transfersRetry(String tradeNo, Integer times) {
        String key = PayConstants.CACHE_KEY_RETRY + ":Transfers:" + tradeNo;
        return requestRetry(key, times, 1L, TimeUnit.DAYS);
    }

    /**
     * 企业付款重试
     * @param tradeNo 交易流水号
     * @return  是否需要重试
     */
    public static Boolean transfersRetry(String tradeNo){
        return transfersRetry(tradeNo, retryCount);
    }

    /**
     * 免密代扣重试
     * @param paymentNo 支付流水号
     * @param times     重试次数
     * @return  是否需要重试
     */
    public static Boolean withholdRetry(String paymentNo, Integer times) {
        String key = PayConstants.CACHE_KEY_RETRY + ":Withhold:" + paymentNo;
        return requestRetry(key, times, 1L, TimeUnit.DAYS);
    }

    /**
     * 免密代扣重试
     * @param paymentNo 支付流水号
     * @return  是否需要重试
     */
    public static Boolean withholdRetry(String paymentNo){
        return withholdRetry(paymentNo, retryCount);
    }

    /**
     * 退款重试
     * @param refundNo  退款流水号
     * @param times     重试次数
     * @return  是否需要重试
     */
    public static Boolean refundRetry(String refundNo, Integer times) {
        String key = PayConstants.CACHE_KEY_RETRY + ":Refund:" + refundNo;
        return requestRetry(key, times, 1L, TimeUnit.DAYS);
    }

    /**
     * 退款重试
     * @param refundNo  退款流水号
     * @return  是否需要重试
     */
    public static Boolean refundRetry(String refundNo){
        return refundRetry(refundNo, retryCount);
    }

    public static Boolean requestRetry(String key, Integer times, Long expire, TimeUnit unit){
        StringRedisTemplate stringRedisTemplate = SpringUtils.getBean("stringRedisTemplate");
        String str = stringRedisTemplate.opsForValue().get(key);
        if(str==null){
            stringRedisTemplate.opsForValue().set(key, "1", expire, unit);
        }else{
            Integer num = Integer.valueOf(str);
            if(num >= times){
                return false;
            }
            stringRedisTemplate.opsForValue().increment(key);
        }
        return true;
    }

}
